package com.greenold.check.service.impl;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.greenold.approvalRecord.domain.ApprovalRecord;
import com.greenold.approvalRecord.mapper.ApprovalRecordMapper;
import com.greenold.check.domain.CheckoutBill;
import com.greenold.check.domain.Dto.CheckOutDto;
import com.greenold.check.mapper.CheckoutBillMapper;
import com.greenold.common.core.domain.entity.SysRole;
import com.greenold.common.core.domain.entity.SysUser;
import com.greenold.common.core.domain.model.LoginUser;
import com.greenold.common.utils.SecurityUtils;
import com.greenold.residing.domain.Contract;
import com.greenold.residing.mapper.ContractMapper;
import com.greenold.service.mapper.CareLevelMapper;
import com.greenold.system.mapper.SysRoleMapper;
import com.greenold.system.mapper.SysUserMapper;
import com.greenold.utils.ActivityUtil;
import com.greenold.utils.OSSUtils;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.greenold.check.mapper.CheckoutMapper;
import com.greenold.check.domain.Checkout;
import com.greenold.check.service.ICheckoutService;
import org.springframework.web.multipart.MultipartFile;

/**
 * 退住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-13
 */
@Service
public class CheckoutServiceImpl implements ICheckoutService {
    @Autowired
    private CheckoutMapper checkoutMapper;
    @Autowired
    private CheckoutBillMapper checkoutBillMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CareLevelMapper careLevelMapper;



    /**
     * 查询退住
     *
     * @param id 退住主键
     * @return 退住
     */
    @Override
    public Checkout selectCheckoutById(String id) {
        return checkoutMapper.selectCheckoutById(id);
    }

    /**
     * 查询退住列表
     *
     * @param checkout 退住
     * @return 退住
     */
    @Override
    public List<Checkout> selectCheckoutList(Checkout checkout) {
        checkout.setStatus("2");
        return checkoutMapper.selectCheckoutList(checkout);
    }


    /**
     * 新增退住
     *
     * @param checkout 退住
     * @return 结果
     */
    @Override
    public String insertCheckout(Checkout checkout) {


        SysUser user = SecurityUtils.getLoginUser().getUser();
        Checkout checkoutTo = new Checkout();
        checkoutTo.setElderId(checkout.getElderId());


        List<Checkout> checkouts = checkoutMapper.selectCheckoutList(checkoutTo);
        if (!checkouts.isEmpty()) {
            return "500";
        }

        String prefix = "TZ";
        String datePart = new SimpleDateFormat("yyMMddHHmm").format(checkout.getCheckoutTime());
        // 获取当天已有的记录数（比如从数据库查询）
        int countToday = checkoutMapper.countToday(checkout.getCheckoutTime());
        // 序列号部分（6位）
        String serial = String.format("%06d", countToday + 1);

        checkout.setCareLevel(careLevelMapper.selectCareLevelById(checkout.getCareLevel()).getLevelName());
        checkout.setCheckoutNo(prefix + datePart + serial);
        checkout.setTitle(checkout.getName() + "的退住申请");
        checkout.setApplicant(user.getNickName());
        checkout.setApplicantId((String.valueOf(user.getUserId())));
        checkout.setApplyTime(new Date());
        checkout.setCreateBy(user.getUserName());
        checkout.setCreatedAt(new Date());
        checkout.setStatus("1");
        checkout.setProcessStatus("1");


        Map<String, Object> params = new HashMap<>();
        params.put("assignee0", checkout.getApplicantId());


        params.put("processTitle",checkout.getTitle());
        params.put("assignee0Name",checkout.getApplicant());
        params.put("processType",2);
        params.put("status", 1);
        params.put("processCode",checkout.getCheckoutNo());
        params.put("applicationTime", new Date());
        ProcessInstance processInstance = ActivityUtil.startProcess("checkout", params);
        checkout.setBusinessId(processInstance.getId());

        params.put("assignee1", "1");
        ActivityUtil.completeTask(processInstance.getId(), params);



        checkoutMapper.insertCheckout(checkout);

        return checkout.getId();
    }

    /**
     * 修改退住
     *
     * @param checkout 退住
     * @return 结果
     */
    @Override
    public int updateCheckout(Checkout checkout) {
        return checkoutMapper.updateCheckout(checkout);
    }

    /**
     * 批量删除退住
     *
     * @param ids 需要删除的退住主键
     * @return 结果
     */
    @Override
    public int deleteCheckoutByIds(String[] ids) {
        return checkoutMapper.deleteCheckoutByIds(ids);
    }

    /**
     * 删除退住信息
     *
     * @param id 退住主键
     * @return 结果
     */
    @Override
    public int deleteCheckoutById(String id) {
        return checkoutMapper.deleteCheckoutById(id);
    }

    @Override
    public String uploadFile(MultipartFile file, String contractNo) {
        try {
            // 获取文件输入流
            InputStream inputStream = file.getInputStream();

            // 调用通用上传方法（这里 folder 可以自行指定）
            String folder = "uploads/pdf/"; // ✅ 存放在 OSS 的目录路径
            return OSSUtils.upload(inputStream, contractNo+".pdf", folder);

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
    }

    @Override
    public CheckOutDto selectCheckoutDtoById(String id) {



        return checkoutMapper.selectCheckOutDtoById(id);
    }

    @Override
    public String addCheckOutBill(String jsonBill, String id, String elderId) {
     //   System.out.println(jsonBill + id + elderId);
        Checkout checkout = checkoutMapper.selectCheckoutById(id);
        System.out.println(checkout.toString());

//        checkOutDto.setProcessStatus("2");
//        checkoutMapper.updateCheckout(checkOutDto);
        CheckoutBill checkoutBill = new CheckoutBill();
        checkoutBill.setCheckoutId(id);
        checkoutBill.setBillJson(jsonBill);
        checkoutBill.setElderId(elderId);
        int i = checkoutBillMapper.insertCheckoutBill(checkoutBill);

        Map<String, Object> params = new HashMap<>();
        params.put("assignee4", "1");

        checkout.setProcessStatus("4");
        checkoutMapper.updateCheckout(checkout);

        ActivityUtil.completeTask(checkout.getBusinessId(),params);

        return "添加成功";
    }


    @Override
    public Map<String, Object> getActivityUser(String id) {
        Checkout checkout = checkoutMapper.selectCheckoutById(id);
        Map<String, Object> map = new HashMap<>();

        if (checkout.getProcessStatus().equals("0")) {
            String checkAssignee = ActivityUtil.getLatestAssignee(checkout.getBusinessId(), "sid-457f727e-2186-4eba-9f62-fe7be29e6bb8");
            HistoricTaskInstance historyTask = ActivityUtil.getHistoryTask(checkout.getBusinessId(), "sid-1fcb1adc-3655-4bc3-afe7-360285353465");
            map.put("appTask", historyTask);
            System.out.println(historyTask.getAssignee() + " " + checkAssignee);
            map.put("appUser", sysUserMapper.selectUserById(Long.parseLong(historyTask.getAssignee())));
            map.put("checkUser", sysUserMapper.selectUserById(Long.parseLong(checkAssignee)));
        } else {//else if (checkout.getProcessStatus().equals("1")) {

            HistoricTaskInstance appTask = ActivityUtil.getHistoryTask(checkout.getBusinessId(), "sid-1fcb1adc-3655-4bc3-afe7-360285353465");
            HistoricTaskInstance checkTask = ActivityUtil.getHistoryTask(checkout.getBusinessId(), "sid-457f727e-2186-4eba-9f62-fe7be29e6bb8");
            map.put("appTask", appTask);
            System.out.println(appTask.getAssignee() + " " + checkTask.getAssignee());
            map.put("appUser", sysUserMapper.selectUserById(Long.parseLong(appTask.getAssignee())));
            map.put("checkUser", sysUserMapper.selectUserById(Long.parseLong(appTask.getAssignee())));
            Comment latestCommentByActivity = ActivityUtil.getLatestCommentByActivity(checkout.getBusinessId(), "sid-457f727e-2186-4eba-9f62-fe7be29e6bb8");
            map.put("comment", latestCommentByActivity);

        }

        return map;
    }
@Autowired
private SysRoleMapper sysRoleMapper;
    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;

    @Override
    public String approval(String num, String checkoutId, String comment) {
        System.out.println("approval");
        System.out.println(num + checkoutId + comment);
        Checkout checkout = checkoutMapper.selectCheckoutById(checkoutId);

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
    //    List<Long> longs = sysRoleMapper.selectRoleListByUserId(user.getUserId());

        ApprovalRecord approvalRecord = new ApprovalRecord();

        approvalRecord.setBusinessId(checkout.getBusinessId());
        approvalRecord.setApprovalType("1");
        approvalRecord.setApproverId(user.getUserId().toString());
        approvalRecord.setApproverName(user.getUserName());
        approvalRecord.setApproverRole(user.getRemark());
        approvalRecord.setUpdateTime(new Date());

        Map<String, Object> params = new HashMap<>();
        if (checkout.getProcessStatus().equals("1")) {
            //退住申请
            if (num.equals("0") ) {

                approvalRecord.setCurrentStep("提出退住申请");
                approvalRecord.setNextStep("解除协议");
                approvalRecord.setApprovalStatus("1");



                checkout.setProcessStatus("2");
                params.put("assignee2", checkout.getApplicantId());
                params.put("num0", num);
                System.out.println("num0  0");
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);

            } else if (num.equals("1")) {
                approvalRecord.setCurrentStep("提出退住申请");
                approvalRecord.setNextStep("解除协议");
                approvalRecord.setApprovalStatus("2");



                System.out.println("num0  1");
                checkout.setStatus("3");
                params.put("num0", num);
                params.put("status", "3");
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);
            }

        }else if(checkout.getProcessStatus().equals("4")){
            //退住审核
            if (num.equals("0")) {
                approvalRecord.setCurrentStep("账单审核");
                approvalRecord.setNextStep("院长审核");
                approvalRecord.setApprovalStatus("1");

                System.out.println("num1  0");
                checkout.setProcessStatus("5");
                params.put("num1", num);
                params.put("status", "3");
                params.put("assignee5", checkout.getApplicantId());
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);
            } else if (num.equals("1") ) {
                approvalRecord.setCurrentStep("账单审核");
                approvalRecord.setNextStep("院长审核");
                approvalRecord.setApprovalStatus("2");

                System.out.println("num0  1");
                checkout.setStatus("3");
                params.put("num1", num);
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);
                System.out.println("num1  1");
            }
        }else if(checkout.getProcessStatus().equals("5")){
            //退住审核
            if (num.equals("0")) {
                approvalRecord.setCurrentStep("院长审核");
                approvalRecord.setNextStep("账单结算");
                approvalRecord.setApprovalStatus("1");

                System.out.println("num1  0");
                checkout.setProcessStatus("6");
                params.put("num2", num);
                params.put("status", "3");
                params.put("assignee6", checkout.getApplicantId());
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);
            } else if (num.equals("1") ) {
                approvalRecord.setCurrentStep("院长审核");
                approvalRecord.setNextStep("账单结算");
                approvalRecord.setApprovalStatus("2");

                System.out.println("num0  1");
                checkout.setStatus("3");
                params.put("num2", num);
                ActivityUtil.addComment(ActivityUtil.getTaskById(checkout.getBusinessId()).getId(), checkout.getBusinessId(), comment);
                ActivityUtil.completeTask(checkout.getBusinessId(), params);
                System.out.println("num1  1");
            }
        }

        approvalRecordMapper.insertApprovalRecord(approvalRecord);

        return checkoutMapper.updateCheckout(checkout) == 1 ? "操作成功" : "操作失败";
    }

    @Override
    public String removeContract(String id, String fileUrl, Date removeData) {
        Checkout checkout = checkoutMapper.selectCheckoutById(id);
        Contract contract=checkoutMapper.selectContractByNo(checkout.getContractNo());
        contract.setCheckoutId( id);
        contract.setTerminateBy(checkout.getApplicantId());
        contract.setTerminateDate(removeData);
        contract.setTerminateAgreementUrl(fileUrl);
     //   contract.setId(checkout.getContractNo());
        Map<String, Object> params = new HashMap<>();
        params.put("assignee3", "1");
        ActivityUtil.completeTask(checkout.getBusinessId(), params);
        contractMapper.updateContract(contract);
        checkout.setProcessStatus("3");

        checkoutMapper.updateCheckout(checkout);



        return "操作成功";
    }

    @Override
    public String uploadRefundVoucher(String id, String refundWay, BigDecimal refundAmount, String refundRemark, MultipartFile refundVoucher) {
        String upload="";
        try {
            // 获取文件输入流
            InputStream inputStream = refundVoucher.getInputStream();
            // 调用通用上传方法（这里 folder 可以自行指定）
            String folder = "uploads/pdf/"; // ✅ 存放在 OSS 的目录路径
             upload = OSSUtils.upload(inputStream, "checkout"+id+refundVoucher.getOriginalFilename(), folder);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败：" + e.getMessage());
        }
        Checkout checkout = checkoutMapper.selectCheckoutById(id);
        checkout.setProcessStatus("7");
        checkout.setStatus("2");

        CheckoutBill checkoutBill = checkoutBillMapper.selectCheckoutBillByCheckId(id);
        checkoutBill.setRefundVoucherUrl(upload);
        checkoutBill.setRefundAmount(refundAmount);
        checkoutBill.setIsRefunded("1");
        checkoutBill.setPayChannel(refundWay);
        checkoutBill.setRemark(refundRemark);
        Map<String, Object> params = new HashMap<>();
        params.put("status", "2");
        checkoutBillMapper.updateCheckoutBill(checkoutBill);
        checkoutMapper.updateCheckout(checkout);

        ActivityUtil.completeTask(checkout.getBusinessId(),null);

        return "操作成功";
    }

    @Override
    public Map<String, Object> getActivityLog(String id) {
        Map<String, Object> map = new HashMap<>();
        Checkout checkout = checkoutMapper.selectCheckoutById(id);
        List<HistoricTaskInstance> historyTasks = ActivityUtil.getHistoryTasks(checkout.getBusinessId());
        map.put("activities",  historyTasks);
        List<Comment> comments = ActivityUtil.getCommentsByProcessInstance(checkout.getBusinessId());

        comments.forEach(c -> {
            map.put(c.getTaskId(), c);
        });
        List<Long> ids= new ArrayList();
        for (HistoricTaskInstance task : historyTasks) {
            if(
                  !ids.contains(Long.valueOf(task.getAssignee()))
            ){
                ids.add(Long.valueOf(task.getAssignee()));
            }
        }
        ids.forEach(userId -> {
         //   sysUserMapper.selectUserById(userId);
            map.put(String.valueOf(userId), sysUserMapper.selectUserById(userId));
        });


        return map;
    }

    @Override
    public Map<String, String> getCheckoutId(String processInstanceId) {
        Map<String, String> map = new HashMap<>();

        System.out.println("processInstanceId = " + processInstanceId);

        // 查询数据库
        Checkout result = checkoutMapper.selectCheckoutByBusinessId( processInstanceId);

        if (result == null ) {

            map.put("checkoutId", null);
            return map;
        }
        System.out.println("result = " + result.toString());

        map.put("checkoutId", result.getId());
        return map;
    }
}

